<template>
  <div class="editor-wrap" :class="{ bor: !editing }">
    <froala
      id="froala-editor"
      :tag="'textarea'"
      :config="froalaConfig"
      v-model="body"
    ></froala>

    <insertAudio
      @insertImage="insertImage"
      :audioDialog="audioDialog"
      :Utoken="Utoken"
      @closeDialog="
        () => {
          audioDialog = false;
        }
      "
    />
    <insertImages
      @insertImage="insertImage"
      :dialogVisible="dialogVisible"
      @closeDialog="
        () => {
          dialogVisible = false;
        }
      "
    />
    <openXiumi
      @insertImage="insertXiumiHtml"
      :xiumiVisible="xiumiVisible"
      @closeDialog="
        () => {
          xiumiVisible = false;
        }
      "
    ></openXiumi>
    <!-- <el-form-item label="主题简介">
      <qzl-froala
        ref="froala"
        :editing="true"
        :height="400"
        :value="item.intro"
        :label="item.intro"
        @blur="(val) => (item.intro = val)"
      ></qzl-froala>
    </el-form-item> -->
  </div>
</template>
<script>
import FroalaEditor from "froala-editor";
import insertImages from "./components/insertImages.vue";
import openXiumi from "./components/openXiumi.vue";
import insertAudio from "./components/insertAudio.vue";

// https://www.cnblogs.com/bremm/p/12792321.html
// froala 需要破解 如果依赖环境是新安装的，需要参考上面的网址删除部分代码
// import util from "@/libs/util";
import { getToken } from "@/utils/auth";

// import qnApi from "@api/plugin.upload";
import { uploadImageToLink } from "@/api/article";

export default {
  name: "froala-editor",
  props: {
    // 显示的工具列表
    tool: {
      type: Array,
      default: (_) => [
        "fullscreen",
        "Word Paste",
        "undo",
        "redo",
        "clearFormatting",
        "bold",
        "italic",
        "underline",
        "strikeThrough",
        // 'fontFamily',
        "fontSize",
        "textColor",
        "backgroundColor",
        "background",
        // 'inlineStyle',
        "paragraphFormat",
        "align",
        // 'formatOL',
        // 'formatUL',
        "outdent",
        "indent",
        "quote",
        "insertLink",
        "insertImage",
        "insertImages",
        "insertVideo",
        "embedly",
        "insertFile",
        "insertAudio",
        "insertTable",
        // 'emoticons',
        // 'specialCharacters',
        "insertHR",
        "selectAll",
        // 'print',
        "spellChecker",
        "close",
        // 'html',
        // 'help',
      ],
    },
    tool1: {
      type: Array,
      default: (_) => [
        "fullscreen",
        "Word Paste",
        "undo",
        "redo",
        "clearFormatting",
        "bold",
        "italic",
        "underline",
        "strikeThrough",
        // 'fontFamily',
        "fontSize",
        "textColor",
        "backgroundColor",
        "background",
        // 'inlineStyle',
        "paragraphFormat",
        "align",
        // 'formatOL',
        // 'formatUL',
        "outdent",
        "indent",
        "quote",
        "insertLink",
        "insertImage",
        "insertImages",
        "insertVideo",
        "embedly",
        "insertFile",
        "insertAudio",
        "insertTable",
        // 'emoticons',
        // 'specialCharacters',
        "insertHR",
        "selectAll",
        "linkXiumi",
        // 'print',
        "spellChecker",
        "close",
        // 'html',
        // 'help',
      ],
    },
    placeholder: {
      type: String,
      //   required: true
    },
    height: {
      type: Number,
    },
    value: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: 1,
    },
    editing: null,
    isJtc: false,
  },
  components: { insertImages, openXiumi, insertAudio },
  created() {
    this.setButtonLinkXiumi();
    this.setButtonInsertImages();
    this.setButtonInsertAudio();
  },
  data() {
    var that = this;
    return {
      Utoken: getToken(),
      // 音频上传盒子开关
      audioDialog: false,
      // 多图上传盒子开关
      dialogVisible: false,
      // 打开秀米盒子开关
      xiumiVisible: false,
      // 光标
      lastEditRange: null,

      editor: null,
      body: null,
      froalaConfig: {
        // editInPopup: true,
        // contenteditable: false,
        // videoDefaultWidth: '100%',
        imageMaxSize: 1024 * 1024 * 100,
        videoMaxSize: 1024 * 1024 * 100,
        fileMaxSize: 1024 * 1024 * 20,
        // imageMultipleStyles: true,
        // imagePasteProcess: true,
        imagePaste: false,
        initOnClick: false,
        charCounterCount: false,
        imageInsertButtons: ["imageBack", "|", "imageUpload"],
        videoInsertButtons: ["videoBack", "|", "videoUpload"],
        colorsBackground: [
          "#2E2E2E",
          "#767676",
          "#DF281B",
          "#F4821C",
          "#46AC43",
          "#2E5BF7",
          "#A249B3",
          "REMOVE",
        ],
        // colorsText: ['#2E2E2E', '#767676', '#DF281B', '#F4821C', '#46AC43', '#2E5BF7', '#A249B3', 'REMOVE'],
        fontSize: ["14", "16", "18", "20", "24", "28", "36", "48", "60"],
        toolbarButtons: that.isJtc ? that.tool1 : that.tool,
        // theme: "dark",//主题
        placeholderText: that.placeholder || "请在此输入",
        language: "zh_cn", //国际化
        imageResizeWithPercent: true,
        // http://192.168.1.184:8083
        imageUploadURL:
          // "http://192.168.1.184:8083/community/article/article/uploadImageToLink",
          // "https://pc.mabababiancheng.com/community/article/article/uploadImageToLink",
          "https://mbpc.mabababiancheng.com/community/article/article/uploadImageToLink",

        // imageUploadURL:"http://i.froala.com/upload",
        imageUploadParams: {
          type: 8,
        },
        // imageUploadParam: "image",
        fileUploadURL:
          // "https://pc.mabababiancheng.com/community/article/article/uploadImageToLink",
          "https://mbpc.mabababiancheng.com/community/article/article/uploadImageToLink",

        // fileUploadURL:"http://i.froala.com/upload",
        fileUploadParams: {
          type: 8,
        },
        videoUploadURL:
          // "https://pc.mabababiancheng.com/community/articleApi/article/uploadImageFWBToLink",
          "https://mbpc.mabababiancheng.com/community/articleApi/article/uploadImageFWBToLink",

        // videoUploadURL:"http://i.froala.com/upload",
        videoUploadParams: {
          type: 8,
        },
        requestHeaders: {
          token: getToken(),
        },
        imageMultipleStyles: true,
        // quickInsertButtons: ['insertImage', 'align', 'insertImage', 'ol', 'hr'], //快速插入项
        toolbarVisibleWithoutSelection: true, //是否开启 不选中模式
        // disableRightClick: true,//是否屏蔽右击
        colorsHEXInput: false, //关闭16进制色值
        toolbarSticky: true, //操作栏是否自动吸顶,
        zIndex: 2501,
        height: that.height || "1000",
        // autofocus: true,
        events: {
          initialized: function () {
            that.editor = this;
            that.setIndex(that.index);
            that.body = that.value;
            if (!that.editing) this.toolbar.hide();
          },
          blur: () => {
            // this.editor.print.run()
            let val = that.getSimpleText(that.editor.html.get(true));
            if (val !== that.label) {
              that.$emit("blur", val);
            }
          },
          "image.beforeUpload": function (files) {
            let file = files[0];
            const isImg =
              file.type === "image/jpeg" ||
              file.type === "image/png" ||
              file.type === "image/gif";
            let limit = 10;
            const isLt = file.size / 1024 / 1024 <= limit;

            if (!isImg) {
              that.$message.error("请上传图片!");
            }
            if (!isLt) {
              that.$message.error(`上传图片大小不能超过 ${limit}MB!`);
            }
            return isImg && isLt;
          },
          "image.inserted": function (a, b) {
            // this.$message('上传成功')
          },
          "image.beforePasteUpload": function (a) {
            console.log(a);
          },
          "file.beforeUpload": function () {
            return true;
          },
          "image.uploaded": function (res) {
            // 图片已上传到服务器。
            console.log(res);
          },
          "video.beforeUpload": function () {
            return true;
          },
          contentChanged: () => {},
          click: function () {
            if (!that.editing) {
              this.edit.off();
            }
          },
          insertImages: {
            title: "多图上传",
          },
          linkXiumi: {
            title: "秀米",
          },
          insertAudio: {
            title: "音频上传",
          },
        },
      },
    };
  },
  watch: {
    body: function (newVal, old) {
      if (old !== newVal) {
        let val = this.getSimpleText(this.editor.html.get(true));
        this.$emit("input", val);
      }
    },
    label: function (newVal, old) {
      if (old !== newVal) {
        this.editor && this.editor.html.set(newVal);
        this.editor.charCounter.count();
      }
    },
    editing: {
      immediate: true,
      handler(val) {
        if (val) {
          this.editor && this.editor.toolbar.show();
        } else {
          this.editor && this.editor.toolbar.hide();
        }
      },
    },
  },
  methods: {
    //更改富文本层级
    setIndex(val) {
      this.$nextTick(() => {
        let dv = document.getElementsByClassName("fr-box");
        for (let i in dv) {
          if (!dv[i].style) {
            return;
          }
          dv[i].style.cssText = "z-index:" + val;
        }
      });
    },
    //富文本中提取纯文本
    getSimpleText: (html) => {
      var re1 = new RegExp('<p data-f-id="pbf".+?</p>', "g"); //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
      var msg = html.replace(re1, ""); //执行替换成空字符
      return msg;
    },
    //重置富文本
    resetValue(val) {
      this.body = val || "";
    },
    print() {
      this.editor && this.editor.print.run();
    },

    // 自定义按钮: 音频上传
    setButtonInsertAudio() {
      let that = this;
      FroalaEditor.DefineIcon("insertAudio", { NAME: "audio", SVG_KEY: "add" });
      FroalaEditor.RegisterCommand("insertAudio", {
        title: "音频上传",
        focus: false,
        undo: false,
        refreshAfterCallback: true,
        callback: function () {
          const selection = that.editor?.selection.get();
          that.lastEditRange = selection?.getRangeAt(0);
          that.audioDialog = true;
        },
      });
    },
    // 自定义按钮: 多图上传
    setButtonInsertImages() {
      let that = this;
      FroalaEditor.DefineIcon("insertImages", {
        NAME: "images",
        SVG_KEY: "imageManager",
      });
      FroalaEditor.RegisterCommand("insertImages", {
        title: "多图上传",
        focus: false,
        undo: false,
        refreshAfterCallback: true,
        callback: function () {
          const selection = that.editor?.selection.get();
          that.lastEditRange = selection?.getRangeAt(0);
          that.dialogVisible = true;
        },
      });
    },
    // 自定义按钮: 跳转秀米
    setButtonLinkXiumi() {
      let that = this;
      FroalaEditor.DefineIcon("linkXiumi", {
        NAME: "xiumi",
        SVG_KEY: "imageCaption",
      });
      FroalaEditor.RegisterCommand("linkXiumi", {
        title: "秀米",
        focus: false,
        undo: false,
        refreshAfterCallback: true,
        callback: function () {
          const selection = that.editor?.selection.get();
          that.lastEditRange = selection?.getRangeAt(0);
          that.xiumiVisible = true;
        },
      });
    },
    insertImage(html) {
      console.log(html);
      //设置编辑器获取焦点
      this.editor.events.focus();
      // 获取选定对象
      const selection = this.editor.selection.get();
      // 判断是否有最后光标对象存在
      if (this.lastEditRange) {
        // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
        selection.removeAllRanges();
        selection.addRange(this.lastEditRange);
      }
      //插入内容
      this.editor.html.insert(html);

      //记录最后光标停留位置
      this.lastEditRange = selection.getRangeAt(0);
    },
    insertXiumiHtml() {},
    // insertXiumiHtml(html) {
    //   let imgReg = /<img.*?(?:>|\/>)/gi; //匹配图片中的img标签
    //   let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; // 匹配图片中的src
    //   let arr = html.match(imgReg); //筛选出所有的img
    //   if (arr) {
    //     for (let i = 0; i < arr.length; i++) {
    //       let src = arr[i].match(srcReg);
    //       // 获取图片地址
    //       var data = {
    //         url: src[1],
    //       };
    //       uploadImageToLink(data).then((res) => {
    //         var url = "http://community.mabababiancheng.com/" + res;
    //         html = html.replace(new RegExp(src[1], "g"), url);
    //         if (i == arr.length - 1) {
    //           //设置编辑器获取焦点
    //           this.editor.events.focus();
    //           // 获取选定对象
    //           const selection = this.editor.selection.get();
    //           // 判断是否有最后光标对象存在
    //           if (this.lastEditRange) {
    //             // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
    //             selection.removeAllRanges();
    //             selection.addRange(this.lastEditRange);
    //           }
    //           //插入内容
    //           this.editor.html.insert(html);

    //           //记录最后光标停留位置
    //           this.lastEditRange = selection.getRangeAt(0);
    //         }
    //       });
    //     }
    //   } else {
    //     //设置编辑器获取焦点
    //     this.editor.events.focus();
    //     // 获取选定对象
    //     const selection = this.editor.selection.get();
    //     // 判断是否有最后光标对象存在
    //     if (this.lastEditRange) {
    //       // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
    //       selection.removeAllRanges();
    //       selection.addRange(this.lastEditRange);
    //     }
    //     //插入内容
    //     this.editor.html.insert(html);

    //     //记录最后光标停留位置
    //     this.lastEditRange = selection.getRangeAt(0);
    //   }
    // },
  },
};
</script>
<style lang="scss">
.editor-wrap {
  width: 100%;

  &.bor {
    border-top: 1px solid #ccc;
  }
}

.editor-wrap > div {
  width: 100%;
}

.fr-wrapper > div[style*="z-index:9999;"],
.fr-wrapper > div[style*="z-index: 9999;"] {
  height: 0;
  overflow: hidden;
}
.fr-wrapper {
  height: 402px !important;
}
.fr-box .second-toolbar #logo {
  width: 0 !important;
  height: 0 !important;
  overflow: hidden;
}

.fr-box .fr-toolbar {
  border-radius: 4px 4px 0 0;
  border-color: #dcdfe6;
}

.fr-box .second-toolbar {
  border-radius: 0 0 4px 4px;
  border-color: #dcdfe6;
}

.fr-box .fr-wrapper {
  border-color: #dcdfe6 !important;
}
</style>
